package com.example.helloworld;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class AsyncTask extends Activity {

	TextView text;
	android.widget.ProgressBar progress;
	BackgroundTask task;
	int value;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_async_task);
		
		text =			(TextView)findViewById(R.id.textStatus);
		progress =		(android.widget.ProgressBar)findViewById(R.id.progress);
		
		Button run =	(Button)findViewById(R.id.run);
		run.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				task =	new BackgroundTask();
				task.execute();
			}
		});
		
		Button cancel =	(Button)findViewById(R.id.cancel);
		cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				task.cancel(true);
			}
		});
	}

	class BackgroundTask extends android.os.AsyncTask<Integer, Integer, Integer> {
		@Override
		protected void onPreExecute() {
			value =	0;
			progress.setProgress(value);
		}
		
		@Override
		protected Integer doInBackground(Integer ... arg0) {
			while (isCancelled() == false) {
				value++;
				
				if (value >= 100) {
					break;
				} else {
					publishProgress(value);
				}
				
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					Log.e("do in background", "error", e);
				}
			}
			
			return null;
		}
		
		@Override
		protected void onProgressUpdate(Integer ... values) {
			progress.setProgress(values[0].intValue());
			text.setText("Current value : " + values[0].toString());
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			progress.setProgress(0);
			text.setText("Finished");
		}
		
		@Override
		protected void onCancelled() {
			progress.setProgress(0);
			text.setText("Cancelled");
		}
	}
	
}
